package com.chao.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.chao.pojo.AccessToken;
import com.chao.pojo.Button;
import com.chao.pojo.CommonButton;
import com.chao.pojo.ComplexButton;
import com.chao.pojo.Menu;
import com.chao.pojo.PhotoOrAlbum;
import com.chao.pojo.ViewButton;
import com.chao.service.CoreService;
import com.chao.util.MyX509TrustManager;
import com.chao.util.SignUtil;
import com.chao.util.WeixinUtil;
/**
 * 核心请求处理类
 * @author Administrator
 *
 */
public class CoreServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	 private static Logger log = LoggerFactory.getLogger(CoreServlet.class);

	/**
	 * 确认请求来自微信服务器
	 * 
	 * @throws IOException
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		// 微信签名
		String signature = request.getParameter("signature");
		// 时间戳
		String timestamp = request.getParameter("timestamp");
		// 随机数
		String nonce = request.getParameter("nonce");
		// 随机数字符串
		String echostr = request.getParameter("echostr");
		PrintWriter out = response.getWriter();
		// 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
		if (SignUtil.checkSignature(signature, timestamp, nonce)) {
			showMenu();
			out.print(echostr);
		}
		out.close();
		out = null;
	}

	/**
	 * 处理微信服务器发来的消息
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO 消息的接收、处理、响应
	       // 将请求、响应的编码均设置为UTF-8（防止中文乱码）   
        request.setCharacterEncoding("UTF-8");  
        response.setCharacterEncoding("UTF-8");  
       
  
        // 调用核心业务类接收消息、处理消息   
        String respMessage = CoreService.processRequest(request);  
          
        // 响应消息   
        PrintWriter out = response.getWriter();  
        System.out.println("Start测试提交");
        System.out.println(respMessage);
        out.print(respMessage);  
        
        String me = searchMenu();
        System.out.println(me);
        System.out.println("End提交");
         
        out.flush();
        out.close();  

	}
	
    /** 
     * 组装菜单数据 
     *  
     * @return 
     */  
    private static Menu getMenu() {  
        CommonButton btn11 = new CommonButton();  
        btn11.setName("天气预报");  
        btn11.setType("click");  
        btn11.setKey("11");  
  
        CommonButton btn12 = new CommonButton();  
        btn12.setName("公交查询");  
        btn12.setType("click");  
        btn12.setKey("12");  
  
        CommonButton btn13 = new CommonButton();  
        btn13.setName("周边搜索");  
        btn13.setType("click");  
        btn13.setKey("13");  
  
        CommonButton btn14 = new CommonButton();  
        btn14.setName("历史上的今天");  
        btn14.setType("click");  
        btn14.setKey("14");
        
        ViewButton btn15 = new ViewButton();
        btn15.setName("页面测试");
        btn15.setKey("34");
        btn15.setType("view");
        btn15.setUrl("http://weixin-test.coding.io/inter");
  
        CommonButton btn21 = new CommonButton();  
        btn21.setName("歌曲点播");  
        btn21.setType("click");  
        btn21.setKey("21");  
  
        CommonButton btn22 = new CommonButton();  
        btn22.setName("经典游戏");  
        btn22.setType("click");  
        btn22.setKey("22");  
  
        CommonButton btn23 = new CommonButton();  
        btn23.setName("美女电台");  
        btn23.setType("click");  
        btn23.setKey("23");  
  
        CommonButton btn24 = new CommonButton();  
        btn24.setName("人脸识别");  
        btn24.setType("click");  
        btn24.setKey("24");  
  
        CommonButton btn25 = new CommonButton();  
        btn25.setName("聊天唠嗑");  
        btn25.setType("click");  
        btn25.setKey("25");  
  
        CommonButton btn31 = new CommonButton();  
        btn31.setName("Q友圈");  
        btn31.setType("click");  
        btn31.setKey("31");  
  
        CommonButton btn32 = new CommonButton();  
        btn32.setName("电影排行榜");  
        btn32.setType("click");  
        btn32.setKey("32");  
  
//        CommonButton btn33 = new CommonButton();  
//        btn33.setName("幽默笑话");  
//        btn33.setType("click");  
//        btn33.setKey("33");
        ViewButton btn33 = new ViewButton();
        btn33.setName("js接口");
        btn33.setKey("33");
        btn33.setType("view");
        btn33.setUrl("http://weixin-test.coding.io/inter");
        
//        ViewButton btn34 = new ViewButton();
//        btn34.setName("百度搜索");
//        btn34.setKey("34");
//        btn34.setType("view");
//        btn34.setUrl("http://www.baidu.com");
        
        ViewButton btn34 = new ViewButton();
        btn34.setName("百度搜索");
        btn34.setKey("34");
        btn34.setType("view");
        btn34.setUrl("http://demo.open.weixin.qq.com/jssdk/");
        
        PhotoOrAlbum btn35 = new PhotoOrAlbum();
        btn35.setName("拍照");
        btn35.setKey("35");
        btn35.setType("pic_photo_or_album");
  
        ComplexButton mainBtn1 = new ComplexButton();  
        mainBtn1.setName("生活助手");  
        mainBtn1.setSub_button(new Button[] { btn11, btn12, btn13, btn14,btn15 });  
  
        ComplexButton mainBtn2 = new ComplexButton();  
        mainBtn2.setName("休闲驿站");  
        mainBtn2.setSub_button(new CommonButton[] { btn21, btn22, btn23, btn24, btn25 });  
  
        ComplexButton mainBtn3 = new ComplexButton();  
        mainBtn3.setName("更多体验");  
        mainBtn3.setSub_button(new Button[] { btn31, btn32, btn33,btn34,btn35});  
  
        /** 
         * 这是公众号xiaoqrobot目前的菜单结构，每个一级菜单都有二级菜单项<br> 
         *  
         * 在某个一级菜单下没有二级菜单的情况，menu该如何定义呢？<br> 
         * 比如，第三个一级菜单项不是“更多体验”，而直接是“幽默笑话”，那么menu应该这样定义：<br> 
         * menu.setButton(new Button[] { mainBtn1, mainBtn2, btn33 }); 
         */  
        Menu menu = new Menu();  
        menu.setButton(new Button[] { mainBtn1, mainBtn2, mainBtn3 });  
  
        return menu;  
    } 
    
    private void showMenu(){
    	// 第三方用户唯一凭证   
        String appId = "wx2f1f0acbadf16f9c";  
        // 第三方用户唯一凭证密钥   
        String appSecret = "d4624c36b6795d1d99dcf0547af5443d";  
  
        // 调用接口获取access_token   
        AccessToken at = WeixinUtil.getAccessToken(appId, appSecret);  
  
        if (null != at) { 
        	System.out.println("创建菜单");
            // 调用接口创建菜单   
            int result = WeixinUtil.createMenu(getMenu(), at.getToken());  
  
            // 判断菜单创建结果   
            if (0 == result)  
                log.info("菜单创建成功！");  
            else  
                log.info("菜单创建失败，错误码：" + result);  
        }  
    }
    private String searchMenu(){
    	String result=null;
    	// 第三方用户唯一凭证   
        String appId = "wx2f1f0acbadf16f9c";  
        // 第三方用户唯一凭证密钥   
        String appSecret = "d4624c36b6795d1d99dcf0547af5443d";  
  
        // 调用接口获取access_token   
        AccessToken at = WeixinUtil.getAccessToken(appId, appSecret);
        
        if (null != at) { 
            // 调用接口创建菜单   
        	JSONObject jsonObject = WeixinUtil.searchMenu(at.getToken());  
  
        	if (null !=jsonObject) {
    			result=jsonObject.toString();
    		}
        }  
        return result;  
    }
}
